<!--  固定表 -->
<template>
  <div>
    <div class="flex">
      <div class="flex-left">
        <div class="navigationBar">
          <label>预置字段目录</label>
          <span @click="showFolder()"
            ><i class="el-icon el-icon-circle-plus"></i
          ></span>
        </div>
        <div class="flex-tree">
          <el-tree
            ref="tree"
            :data="data"
            node-key="id"
            :render-content="renderContent"
            @node-click="handleNodeClick"
            :highlight-current="true"
          >
          </el-tree>

          <!-- <div
						v-if="data.length == 0"
						style="text-align: center; margin-top: 100px; color: #666"
					>
						暂无数据
					</div> -->
        </div>
      </div>
      <div class="flex-right">
        <navigation-bar>
          <div class="searchContent">
            <el-input
              v-model="username"
              placeholder="请输入字段名称"
              size="mini"
              style="width: 150px; margin-right: 10px"
              @keyup.enter.native="searchClick"
            ></el-input>
            <custom-button
              type="search"
              style="margin-right: 10px"
              @searchClick="searchClick"
            ></custom-button>
            <custom-button
              type="reset"
              style="margin-right: 10px"
              @resetClick="resetClick"
            ></custom-button>
            <custom-button type="add" @addClick="addClick"></custom-button>
            <!-- <el-button
							size="mini"
							style="
								margin-right: 10px;
								background-color: #fc6a6e;
								color: #fff;
								border: none;
							"
							@click="deleteAll"
						>
							<i class="el-icon-delete"></i> 批量删除
						</el-button> -->
          </div>
        </navigation-bar>
        <table-index
          :dataSource="dataSource"
          :tableColumns="tableColumns"
          :btnList="btnList"
          :pageSize="pageSize"
          :pageCount="pageCount"
          :pageNo="pageNo"
          btnListWidth="150"
          @pageChange="pageChange"
          @editRow="editRow"
          @viewRow="viewRow"
          @deleteRow="deleteRow"
          @handleSelectionChange="handleSelectionChange"
        ></table-index>
      </div>
    </div>
    <div v-if="dialogShow">
      <custom-dialog
        :title="dialogTitle"
        size="large"
        @dialogClose="dialogClose"
      >
        <form-index
          :formConfig="formConfig"
          @submit="submit"
          :type="type"
          @formInputChange="formInputChange"
          ref="form"
        >
        </form-index>
      </custom-dialog>
    </div>

    <div v-if="dialogFolderShow">
      <custom-dialog
        :title="dialogFolderTitle"
        size="large"
        @dialogClose="dialogFolderClose"
      >
        <form-index
          :formConfig="formConfigFolder"
          @submit="folderSubmit"
          :type="typeFolder"
          @formInputChange="formInputFolderChange"
          ref="form"
        >
        </form-index>
      </custom-dialog>
    </div>
  </div>
</template>

<script>
import { presetFieldsForm } from "@/assets/form/managementCenter/expandManage/presetFieldsForm";
import { resourceFolderForm } from "@/assets/form/managementCenter/resourceFolderForm";
import customDialog from "@/components/customComponents/customDialog";
import customButton from "@/components/customComponents/customForm/customButton";
import formIndex from "@/components/customComponents/customForm/formIndex";
import tableIndex from "@/components/customComponents/customeTable/tableIndex.vue";
import navigationBar from "@/components/customComponents/managementCenter/navigationBar";
import { AjaxCommon } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import { SessionCommon } from "@/libs/sessionCommon";
import { Utility } from "@/libs/utility";
export default {
  components: {
    navigationBar,
    customButton,
    tableIndex,
    customDialog,
    formIndex,
  },
  data() {
    return {
      curHeight: 100,
      folderData: null,
      fatherFolderId: "0",
      dialogFolderTitle: "新增目录",
      formConfigFolder: resourceFolderForm,
      typeFolder: "add",
      dialogFolderShow: false,
      data: [],
      tableIndex: "",
      selectItem: [],
      username: "",
      // table 相关参数  begin
      dataSource: [],
      tableColumns: [
        {
          prop: "Name",
          label: "字段名",
        },
        {
          prop: "DefaultValue",
          label: "默认值",
        },
        {
          prop: "Descript",
          label: "描述",
        },
      ],
      btnList: ["edit", "delete"],
      pageSize: 20,
      pageCount: 100,
      pageNo: 1,
      // table 相关参数  end

      // 弹窗是否显示
      dialogShow: false,
      // 弹窗标题 (新增修改不同)
      dialogTitle: "",

      // form的配置信息
      formConfig: presetFieldsForm,
      type: "add",
    };
  },
  methods: {
    getData(e) {
      e.FileFolderId = this.tableIndex;
      let self = this;
      AjaxCommon(`/api/ResourceFile/uploadfile`, "postForm", e).then((res) => {
        console.log(res, "3333");
        if (res.data.status == 200) {
          PopupCommon.notify("success", "新增成功");
          self.initPage();
          self.dialogShow = false;
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    handleNodeClick(data) {
      this.tableIndex = data.id;
      this.initPage();
    },
    // 懒加载获取树形结构
    loadNode(node, resolve) {
      console.log(node.level, node.data.id);
      if (node.level == 0) {
        // node其实是需要展开树节点，但是第一次的node是个无用的数据，可以认为这个node是element给我们创建的，判断的话，就是level等于0
        this.getTreeData(0, resolve);
      } else {
        this.getTreeData(node, resolve);
      }
    },
    // 获取树形结构的数据
    getTreeData(node, resolve) {
      var searchNodeID = node ? node.data.id : null;
      AjaxCommon(
        `/api/folder?folderType=1&key=${searchNodeID}`,
        "get",
        null
      ).then((res) => {
        if (res.data.status == 200) {
          var data = res.data.response;
          data = data.map((r) => {
            return {
              id: r.Id,
              label: r.FolderName,
              children: [],
            };
          });
          console.log(data, "data.......");
          if (!node) {
            return resolve(data); // resolve是一个函数，它会接受一个数组，作为你要展开的节点的孩子节点，如果没有孩子节点，直接传一个空数组
          } else {
            if (data && data.length > 0) {
              return resolve(data); // 如果需要设置一个树节点，也可以在这里设置，比如说设置这个孩子节点是叶子节点（也就是不能展开的末节点），可以给其中的数据设置item.isLeaf = true
            } else {
              return resolve([]);
            }
          }
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    append(data) {
      console.log(data, "data.................");
      this.folderData = data;
      this.fatherFolderId = data.id;
      this.typeFolder = "add";
      this.dialogFolderTitle = "新增分类";
      this.dialogFolderShow = true;
    },
    remove(node, data) {
      console.log(node, data, "......................data");
      let self = this;
      const id = data.id;
      PopupCommon.confirm(`确定删除【${data.label}】？`)
        .then(() => {
          AjaxCommon("/api/folder/Delete?id=" + id, "delete", {
            optReason: "删除",
          }).then((res) => {
            console.log(res, "res...............");
            if (res.data.status == 200) {
              PopupCommon.notify("success", "删除成功");
              self.initLeftFolder(() => {
                self.initPage();
              });
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    renderContent(h, { node, data }) {
      // 删除按钮，暂时隐藏。放在tree-btn  类里面
      return (
        <span style="flex: 1;display: flex;align-items: center;justify-content: space-between;font-size: 14px;padding-right: 8px;">
          <span>{node.label}</span>
          <span class="tree-btn">
            <span style="color: #409EFF;padding: 2px;border-radius: 2px;margin-right: 4px;">
              <i class="el-icon-plus" on-click={() => this.append(data)}></i>
            </span>
            <span style="padding: 2px;color: red;border-radius: 2px;">
              <i
                class="el-icon-delete"
                on-click={() => this.remove(node, data)}
              ></i>
            </span>
          </span>
        </span>
      );
    },
    editRow(d) {
      this.type = "edit";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "编辑" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    dialogFolderClose() {
      this.dialogFolderShow = false;
    },
    formInputFolderChange(e) {
      console.log(e, "e...................");
    },
    folderSubmit(d) {
      let self = this;
      var params = {
        FolderName: d.FolderName,
        FatherFolderId: self.fatherFolderId,
        FolderType: 1,
      };
      var titleOpr = "新增成功";
      if (d.Id) {
        params["Id"] = d.Id;
        titleOpr = "编辑成功";
      }
      AjaxCommon(`/api/folder`, "postForm", params)
        .then((res) => {
          console.log(res, "res..................");
          if (res.data.status == 200) {
            PopupCommon.notify("success", titleOpr);
            if (self.fatherFolderId != "0") {
              const newChild = {
                id: res.data.response,
                label: d.FolderName,
                children: [],
              };
              if (!self.folderData.children) {
                this.$set(self.folderData, "children", []);
              }
              self.folderData.children.push(newChild);
            } else {
              self.initLeftFolder();
            }
            self.dialogFolderClose();
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        })
        .catch((err) => {
          PopupCommon.notify("error", err.message);
        });
    },
    showFolder() {
      this.fatherFolderId = "0";
      this.typeFolder = "add";
      this.dialogFolderTitle = "新增分类";
      this.dialogFolderShow = true;
    },
    deleteFolder(item) {
      let self = this;
      const id = item.Id;
      console.log(item, "item");
      PopupCommon.confirm(`确定删除【${item.FolderName}】？`)
        .then(() => {
          AjaxCommon("/api/familyfolder/Delete?id=" + id, "delete", {
            optReason: "删除",
          }).then((res) => {
            console.log(res, "res...............");
            if (res.data.status == 200) {
              PopupCommon.notify("success", "删除成功");
              self.initLeftFolder();
              self.dialogFolderClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          });
        })
        .catch(() => {
          console.log("取消");
        });
    },
    singleBtnClick() {
      if (this.yzzdSelect.length == 0) {
        PopupCommon.notify("info", "请选择预置字段");
        return;
      }
      this.dialogShow = false;
      console.log(this.yzzdSelect, "this.yzzdSelect......");
    },
    singleHandleSelectionChange(e) {
      this.yzzdSelect = e;
    },
    deleteAll() {
      if (this.selectItem.length == 0) {
        PopupCommon.notify("info", "请先勾选数据");
        return;
      }
      PopupCommon.confirm("此操作将删除选择的数据, 是否继续?")
        .then(() => {
          // self.optReason = ""
          // self.dialogVisible = true
          // // optReason
          // const data = {
          // 	index: i,
          // 	data: d[i],
          // }
          // self.formData = data
          // // this.$emit("deleteRow", data)
          console.log(this.selectItem);
        })
        .catch(() => {
          // 这里尽量写下，否则会报警告异常。
          console.log("已取消删除");
        });
    },
    handleSelectionChange(d) {
      this.selectItem = d;
      console.log(d);
    },
    formInputChange(e) {
      // if (e.filedName == "idCard") {
      // 	const data = CardId.getInfoByCardId(e.value)
      // 	if (data) {
      // 		let newData = e.allData
      // 		newData["birthday"] = data.birthday
      // 		newData["sex"] = data.sex
      // 		this.$refs.form.changeFormValue(newData)
      // 	}
      // }
      console.log(e);
    },
    submit(d) {
      let self = this;
      console.log(d);
      d.FolderID = this.tableIndex;
      if (d.Id) {
        AjaxCommon("/api/PresetFieIdController", "postForm", d)
          .then((res) => {
            if (res.data.status == 200) {
              PopupCommon.notify("success", "编辑成功");
              self.initPage();
              self.dialogClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          })
          .catch((err) => {
            PopupCommon.notify("error", err.message);
          });
      } else {
        delete d.Id;
        AjaxCommon("/api/PresetFieIdController", "postForm", d)
          .then((res) => {
            if (res.data.status == 200) {
              PopupCommon.notify("success", "新增成功");
              self.initPage();
              self.dialogClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          })
          .catch((err) => {
            PopupCommon.notify("error", err.message);
          });
      }
    },
    dialogClose() {
      this.dialogShow = false;
    },
    searchClick() {
      this.pageNo = 1;
      this.initPage();
    },
    resetClick() {
      this.username = "";
      this.searchClick();
    },
    addClick() {
      if (this.tableIndex == "") {
        PopupCommon.notify("info", "请先选择左侧的目录");
        return;
      }
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = "";
          }
        });
      });
      this.formConfig = formConfigItem;
      this.type = "add";
      this.dialogShow = true;
      this.dialogTitle = "新增字段";
    },
    // 分页点击事件
    pageChange(p) {
      this.pageNo = p;
      this.initPage();
    },
    viewRow(d) {
      this.type = "look";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "查看" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    downloadRow(d) {
      const id = d.data.Id;
      // let self = this;
      AjaxCommon("/api/ResourceFile/downloadfile/" + id, "getBlob", null).then(
        (res) => {
          if (res.status == 200) {
            // var data = self.stringToArrayBuffer(res.data);
            var blob = new Blob([res.data]);
            const href = URL.createObjectURL(blob);
            const link = document.createElement("a");
            link.download = d.data.FileName;
            link.href = href;
            link.click();
            try {
              document.body.removeChild(link);
            } catch (error) {
              console.log(error.message);
            }
            URL.revokeObjectURL(href); // 释放内存
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        }
      );
    },
    stringToArrayBuffer(str) {
      console.log(str, "str....................");
      var buf = new ArrayBuffer(str.length);
      var bufView = new Uint8Array(buf);
      for (var i = 0, strLen = str.length; i < strLen; i++) {
        bufView[i] = str.charCodeAt(i);
      }
      return buf;
    },
    deleteRow(d) {
      console.log(d);
      const id = d.data.Id;
      let self = this;
      AjaxCommon("/api/PresetFieIdController?id=" + id, "delete", {
        optReason: d.optReason,
      }).then((res) => {
        console.log(res, "res...............");
        if (res.data.status == 200) {
          PopupCommon.notify("success", "删除成功");
          self.initPage();
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    // 初始化事件
    initPage() {
      let self = this;
      var id = this.tableIndex;
      AjaxCommon(
        `/api/PresetFieIdController?page=${this.pageNo}&intPageSize=${this.pageSize}&FolderId=${id}&key=${this.username}`,
        "get"
      ).then((res) => {
        if (res.data.status == 200) {
          self.dataSource = res.data.response.data;
          self.pageCount = res.data.response.pageCount;
        } else {
          PopupCommon.notify("error", res.data.msg);
        }
      });
    },
    initLeftFolder(callback) {
      let self = this;
      self.data = [];
      AjaxCommon("/api/folder/GetFullFolder?FolderType=1", "get", null).then(
        (res) => {
          if (res.data.status == 200) {
            let treeDataList = [];
            Utility.createTreeData(res.data.response, treeDataList);
            self.data = treeDataList;
            if (treeDataList && treeDataList.length > 0) {
              console.log("1111111111111");
              self.tableIndex = treeDataList[0].id;
              self.$nextTick(() => {
                self.$refs.tree.setCurrentKey(treeDataList[0].id);
              });
              callback && callback();
            } else {
              self.tableIndex = "";
              self.tableList = [];
            }
          } else {
            PopupCommon.notify("error", res.data.msg);
          }
        }
      );

      // let self = this
      // self.data = []
      // AjaxCommon("/api/folder?folderType=1", "get", null).then((res) => {
      // 	if (res.data.status == 200) {
      // 		var data = res.data.response
      // 		data = data.map((r) => {
      // 			return {
      // 				id: r.Id,
      // 				label: r.FolderName,
      // 				children: [],
      // 			}
      // 		})
      // 		self.data = data
      // 		setTimeout(() => {
      // 			if (data && data.length > 0) {
      // 				console.log("self...............................")
      // 				self.tableIndex = data[0].id
      // 				self.$nextTick(() => {
      // 					self.$refs.tree.setCurrentKey(data[0].id)
      // 				})
      // 				callback && callback()
      // 			} else {
      // 				self.tableIndex = ""
      // 				self.tableList = []
      // 			}
      // 		}, 1000)
      // 	} else {
      // 		PopupCommon.notify("error", res.data.msg)
      // 	}
      // })
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initLeftFolder(() => {
        this.initPage();
      });
    });
  },
};
</script>

<style scoped>
.flex {
  display: flex;
}

.flex .flex-left {
  width: 350px;
  margin-right: 10px;
}

.flex .flex-right {
  flex: 1;
}

.flex .flex-left .navigationBar {
  height: 36px;
  line-height: 36px;
  background-color: #fff;
  margin-top: 10px;
}

.flex .flex-left .flex-tree {
  background-color: #fff;
  margin-top: 10px;
  height: calc(100vh - 168px);
  overflow-y: auto;
  padding: 10px;
}

.flex .flex-left .flex-tree .tree-item {
  height: 32px;
  line-height: 32px;
  margin: 5px 10px;
  padding: 0 10px;
  font-size: 14px;
  cursor: pointer;
}
.flex .flex-left .flex-tree .tree-item:hover {
  background-color: #e4f1fe;
}
.flex .flex-left .flex-tree .hover {
  background-color: #e4f1fe;
}

.flex .flex-left .navigationBar label {
  text-align: left;
  font-size: 16px;
  color: #333;
  margin-left: 10px;
}

.flex .flex-left .navigationBar span {
  float: right;
  margin-right: 10px;
  color: #333;
  cursor: pointer;
}

.singleTable {
  margin-bottom: 20px;
}
.singleBtn {
  position: absolute;
  bottom: 8px;
  right: 9px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.tree-btn {
  color: red;
}
</style>
